package com.bf.electroplating.service.compoent;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.annotation.PreDestroy;

/**
 * HJ212服务管理器
 * 负责管理HJ212服务器的生命周期
 */
@Slf4j
@Component
public class HJ212ServiceManager {
    
    @Autowired
    private HJ212Server hj212Server;
    
    /**
     * 启动HJ212服务
     */
    public void startService() {
        try {
            if (!hj212Server.isRunning()) {
                hj212Server.startServer();
                log.info("HJ212服务启动成功");
            } else {
                log.info("HJ212服务已在运行中");
            }
        } catch (Exception e) {
            log.error("启动HJ212服务失败", e);
        }
    }
    
    /**
     * 停止HJ212服务
     */
    public void stopService() {
        try {
            if (hj212Server.isRunning()) {
                hj212Server.stopServer();
                log.info("HJ212服务已停止");
            } else {
                log.info("HJ212服务未在运行");
            }
        } catch (Exception e) {
            log.error("停止HJ212服务失败", e);
        }
    }
    
    /**
     * 重启HJ212服务
     */
    public void restartService() {
        log.info("重启HJ212服务");
        stopService();
        try {
            Thread.sleep(1000); // 等待1秒
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        startService();
    }
    
    /**
     * 获取服务状态
     */
    public boolean isServiceRunning() {
        return hj212Server.isRunning();
    }
    
    /**
     * 应用关闭时停止服务
     */
    @PreDestroy
    public void destroy() {
        log.info("应用关闭，停止HJ212服务");
        stopService();
    }
} 